import {Component, OnInit, OnChanges} from '@angular/core';
import {FormArray, FormBuilder, FormGroup, Validators, FormControl, AbstractControl, Form} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import {ResponseUtil} from "../../../../../util/response-util";
import {OneDialogService} from "../../../../../widgets/one-dialog/one-dialog.service";
import {PageSubject} from "../../../../../util/page-subject";
import {Path} from "../../../../../portal/admin/admin-breadcrumb/breadcrumb";
import {MsgResult} from "../../../../../models/msg-result";
import {MsgConstants} from "../../../../../constants/constants";
import {EncircledAreaService} from "../encircled-area.service";
import {Sites} from "../sites";
import {Area,MapPoint} from "../area";
import {typeSourceSpan} from "@angular/compiler";



@Component({
  selector: 'app-encircled-area-add',
  templateUrl: './encircled-area-add.component.html',
  styleUrls: ['./encircled-area-add.component.css']
})
export class EncircledAreaAddComponent implements OnInit,OnChanges {

  area : Area;
  sites:Sites;
  areaForm : FormGroup;
  constructor(
    private router :Router,
    private route :ActivatedRoute,
    private pageSubject : PageSubject,
    private fb : FormBuilder,
    private dialogService :OneDialogService,
    private responseUtil : ResponseUtil,
    private encircledAreaService : EncircledAreaService

  ) {
    this.initObject();
  }

  ngOnInit() {
    this.pushPage();
    this.initSiteInfos();
  }

  private initObject() {
    this.area = new Area();
    this.buildForm();
    this.addMapPoint();
  }

  addMapPoint() {
    this.pointList.push(this.fb.group({
      pointId:'',
      orderNum:['', [Validators.required,Validators.maxLength(5),Validators.pattern(/^[1-9]*[1-9][0-9]*$/)]],
      pointAddress: ['', [Validators.required,Validators.minLength(10),Validators.maxLength(100)]],
      lon: ['', [Validators.required,Validators.maxLength(15),Validators.pattern(/^(((\d|[1-9]\d|1[1-7]\d|0)\.\d{0,6})|(\d|[1-9]\d|1[1-7]\d|0{1,5})|180\.0{0,6}|180)$/)]],
      lat: ['', [Validators.required,Validators.maxLength(15),Validators.pattern(/^([0-8]?\d{1}\.\d{0,6}|90\.0{0,6}|[0-8]?\d{1}|90)$/)]]
    }));
  }
  /**
   * 面包屑
   */
  private pushPage(){
    let path =new Path("电子合围区","");
    this.pageSubject.pushPage("电子合围区","添加",path);
  }
  /**
   * 初始化站点数据
   */
  initSiteInfos(){
    this.encircledAreaService.findSitesInfos().subscribe(
      result =>this.responseUtil.success(result ,this.processSitesResult),
      error => this.responseUtil.error(error)
    );
  }
  private processSitesResult = (result: MsgResult) => {
    if (result && result.code == MsgConstants.MSG_CODE_OK) {
      this.sites = result.data;

    }
    if (result && result.code != MsgConstants.MSG_CODE_OK) {
      this.dialogService.info(result.message);
    }
  }



  /**
   * 构造表单
   */
  private buildForm():void{
    this.areaForm=this.fb.group({
      id: [this.area.id],
      areaName: [this.area.areaName,[
        Validators.required,
        Validators.minLength(3),
        Validators.maxLength(20)
      ]],
      siteCode: [this.area.siteCode,[
        Validators.required
      ]],
      pointList: this.fb.array([])
    });


    this.areaForm.valueChanges.subscribe(
      data => this.onValueChanged(data)
    );
    this.onValueChanged();
  }
  ngOnChanges() {
    this.areaForm.reset();
    this.setMapPoints(this.area.mapPoints);

  }

  setMapPoints(mapPoints: MapPoint[]) {
    const mapPointFGs = mapPoints.map(mapPoint => this.fb.group(mapPoint));
    const mapPointFormArray = this.fb.array(mapPointFGs);
    this.areaForm.setControl('pointList', mapPointFormArray);
  }



  get pointList(): FormArray {
    return this.areaForm.get('pointList') as FormArray;
  }




  private onValueChanged(data ?: any) {
    if (!this.areaForm) {
      return;
    }
    const form = this.areaForm;
    for (const field in this.formErrors) {
    console.log(this.formErrors[field]);
      this.formErrors[field] = '';
      let control = form.get(field);
      let checkControls =[];
      if(!control){
        let formArray = form.get('pointList') as FormArray;
        if(formArray && formArray.length > 0 && formArray.controls.length > 0){
          formArray.controls.forEach(function (formControl) {
            let fc = formControl.get(field);
            if(fc && !fc.valid){
              checkControls.push(fc);
            }
          })

        }
      }else{
        checkControls.push(control);
      }
      checkControls.forEach(function (control) {
        if (control && control.dirty && !control.valid) {
            const messages = this.validationMessages[field];
            for (const key in control.errors) {
              this.formErrors[field] += messages[key] + ' ';
            }
        }
      },this);
    }
  }

  /**
   * 校验字段
   * @type {{areaName: string; pointAddress: string; lon:number; lat:number}}
   */
  formErrors = {
    'areaName': '',
    'siteCode':'',
    'orderNum':'',
    'pointAddress': '',
    'lon': '',
    'lat': ''
  };

  validationMessages = {
    'areaName': {
      'required': '合围区名称不能为空',
      'minlength':'长度不能小于3',
      'maxlength': '长度不能超过20'
    },
    'siteCode': {
      'required': '请选择站点'
    },
    'orderNum': {
      'required': '序号不能为空',
      'pattern': '序号格式不正确',
      'maxlength': '长度不能超过5',
    },
   'pointAddress': {
      'required': '点位位置不能为空',
      'maxlength': '长度不能超过100',
      'minlength':'长度不能小于10'
    },
    'lon': {
      'required': '经度不能为空',
      'pattern': '经度格式不正确',
      'maxlength': '长度不能超过15',
    },
    'lat': {
      'required': '纬度不能为空',
      'maxlength': '长度不能超过15',
      'pattern': '纬度格式不正确'
    }
  }

  prepareSaveArea(): Area {
    const formModel = this.areaForm.value;

    // deep copy of form model lairs
    const pointListDeepCopy: MapPoint[] = formModel.pointList.map(
      (mapPoint: MapPoint) => Object.assign({}, mapPoint)
    );


    const saveArea: Area = {
      id: this.area.id,
      areaName: formModel.areaName as string,
      siteCode:formModel.siteCode as string,
      mapPoints: pointListDeepCopy
    };
    return saveArea;
  }


  /**
   * 实现添加
   */
  onSubmit() {
    this.area = this.prepareSaveArea();
    this.encircledAreaService.add(this.area).subscribe(
      result => this.responseUtil.success(result, this.processAreaResult),
      message => this.responseUtil.error(message)
    );
  }


  /**
   *  处理保存结果
   * @param result
   */
  private processAreaResult= (result : MsgResult) => {
    if(result && result.code == MsgConstants.MSG_CODE_OK){
      this.dialogService.success("添加成功",()=>this.cancelAreaAdd());
    }
    if(result && result.code != MsgConstants.MSG_CODE_OK){
      this.dialogService.info(result.message);
    }
  }
  remove(i) {
         //删除一行

       this.pointList.controls.splice(i, 1);
       this.pointList.removeAt(i);
       this.areaForm.updateValueAndValidity();


  }

  cancelAreaAdd(){
    this.router.navigate(['..'],{relativeTo : this.route});
  }

}
